/**@file
 * @brief etTcl.h实现
 * @see etTcl.h
 * @author <libxiangnan@gmail.com>
 * @date 2011/11/17
 * @version 0.0.1
 * @note
 * This file includes etTcl.h's implementation.
 * */

#include <iostream>
#include <string>
#include <tcl.h>
#include <ctime>
#include <cstdlib>
#include <assert.h>

#include "interp.h"
#include "result.h"
#include "script.h"

using namespace std;

tcl::Interp::Interp() :
		m_Interp(NULL), m_Libpath(""), m_LstScr(dat::Script()) {
	;
}

tcl::Interp::Interp(Tcl_Interp *interp, const std::string & libpath) :
		m_Interp(interp), m_Libpath(libpath), m_LstScr(dat::Script()) {
	;
}

tcl::Interp::~Interp() {
	if (NULL != m_Interp) {
		if (0 == Tcl_InterpDeleted(m_Interp)) {
			Tcl_DeleteInterp(m_Interp);
		}
	}
}

bool tcl::Interp::CreateTclInterpreter() {
	m_Interp = Tcl_CreateInterp();
	Tcl_Init(m_Interp);
	if (NULL != m_Interp) {
		return true;
	} else {
		return false;
	}
}

void tcl::Interp::ConfigInterp() {
	;
}

bool tcl::Interp::ExecuteScript(dat::Script & scr) {
	m_LstScr = scr;
	if (NULL == m_Interp)
		return false;

	const char *fulpath = m_LstScr.getFulpath().c_str();
	if (NULL == fulpath)
		return false;

	if (TCL_OK != Tcl_EvalFile(m_Interp, fulpath)) {
		cout << std::time(NULL) << ": " << fulpath << " failed" << endl;
		return false;
	} else {
		// 更新m_LstScr结果信息
		cout << std::time(NULL) << ": " << fulpath << " succeed" << endl;
		return true;
	}
}

dat::Result tcl::Interp::GetLastScriptResult() {
	return m_LstScr.GetResult();
}

const Tcl_Interp * const tcl::Interp::GetTclInterp() {
	return m_Interp;
}

bool tcl::Interp::CheckTclInterp() {
	if (NULL != m_Interp) {
		return true;
	} else {
		return false;
	}
}

void tcl::Interp::SetLibPath(const std::string & libpath) {
	m_Libpath = libpath;
}

std::string tcl::Interp::GetLibpath() {
	return m_Libpath;
}

dat::Script tcl::Interp::GetLstScr() {
	return m_LstScr;
}

const std::string tcl::Interp::M_TOTAL = "uicc::Total";
const std::string tcl::Interp::M_SUCCESS = "uicc::Success";
const std::string tcl::Interp::M_FAILURE = "uicc::Failure";
const std::string tcl::Interp::M_LOGPATH = "uicc::LogPath";

